package com.yexiang.chargestation.wxapi;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.idbk.chargestation.alipay.PayResult;
import com.android.volley.VolleyError;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonAlipay;
import com.idbk.chargestation.bean.JsonWxPay;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.GsonUtils;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.lang.ref.WeakReference;

/**
 * 充值界面
 *
 * @author lupc, zhx
 */

public class WXPayEntryActivity extends BaseActivity implements OnClickListener, IWXAPIEventHandler {

    private static final String TAG = WXPayEntryActivity.class.getSimpleName();
    /**
     * 支付方式：支付宝
     */
    public final static int PAY_WITH_ALIPAY = 0;
    /**
     * 支付方式：微信
     */
    public final static int PAY_WITH_WECHAT = 1;
    /**
     * 支付方式标志
     */
    private int mFlagPay = PAY_WITH_ALIPAY;
    /**
     * 当前的充值金额，默认500
     */
    private int mIndexPAY = 0;
    private static final int SDK_PAY_FLAG = 1;
    private static final int MONEY_500 = 0;
    private static final int MONEY_200 = 1;
    private static final int MONEY_100 = 2;
    private static final int MONEY_50 = 3;
    private static final int MONEY_CUSTOM = 4;

    private Context mContext;
    private TextView[] mTexMoneyArrays;
    private TextView mTexMoney_500, mTexMoney_200, mTexMoney_100, mTexMoney_50, mTexMoney_xx;//金额
    private EditText mEdtInputMoney;//金额输入
    private RelativeLayout mLayoutAlipay, mLayoutWechat;

    private String mAlipaySign;//支付宝支付签名
    private static int mTradingNumber;//交易流水号

    private final IWXAPI msgApi = AppContext.getInstance().getWxApi();
    private IWXAPI api;
    private AlipayHandle alipayHandle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_recharge);

        mContext = WXPayEntryActivity.this;

        api = WXAPIFactory.createWXAPI(this, getResources().getString(R.string.weixin_app_id));

        api.handleIntent(getIntent(), this);

        initView();

        initData();
    }

    private void initView() {
        setupToolBar2();//显示标题栏
        initEditText();
        initTextView();
        initTextViewArray();
        initLayout();
        initOnClickView();
    }

    private void initEditText() {
        mEdtInputMoney = (EditText) findViewById(R.id.money);
        if (mEdtInputMoney != null) {
            mEdtInputMoney.setFilters(new InputFilter[]{pointFilter});//过滤只能输入两位小数
        }
    }

    private void initTextView() {
        mTexMoney_500 = (TextView) findViewById(R.id.money_five_hundred);
        mTexMoney_200 = (TextView) findViewById(R.id.money_two_hundred);
        mTexMoney_100 = (TextView) findViewById(R.id.money_hundred);
        mTexMoney_50 = (TextView) findViewById(R.id.money_fivty);
        mTexMoney_xx = (TextView) findViewById(R.id.money_other);
    }

    private void initTextViewArray() {
        mTexMoneyArrays = new TextView[5];
        mTexMoneyArrays[MONEY_500] = mTexMoney_500;
        mTexMoneyArrays[MONEY_200] = mTexMoney_200;
        mTexMoneyArrays[MONEY_100] = mTexMoney_100;
        mTexMoneyArrays[MONEY_50] = mTexMoney_50;
        mTexMoneyArrays[MONEY_CUSTOM] = mTexMoney_xx;
    }

    private void initLayout() {
        mLayoutAlipay = (RelativeLayout) findViewById(R.id.activity_money_alipay);
        mLayoutWechat = (RelativeLayout) findViewById(R.id.activity_money_wechat);
    }

    @SuppressWarnings("ConstantConditions")
    private void initOnClickView() {
        for (int i = 0; i < mTexMoneyArrays.length; i++) {
            mTexMoneyArrays[i].setOnClickListener(this);
        }
        findViewById(R.id.submit_recharge).setOnClickListener(this);
        mLayoutAlipay.setOnClickListener(this);
        mLayoutWechat.setOnClickListener(this);
    }

    private void initData() {
        setTextViewData();
        alipayHandle = new AlipayHandle(WXPayEntryActivity.this);
        msgApi.registerApp(getResources().getString(R.string.weixin_app_id));
    }

    private void setTextViewData() {
        mTexMoney_500.setText(getSpannableString("500元", 3, 4));
        mTexMoney_200.setText(getSpannableString("200元", 3, 4));
        mTexMoney_100.setText(getSpannableString("100元", 3, 4));
        mTexMoney_50.setText(getSpannableString("50元", 2, 3));
    }

    private SpannableString getSpannableString(String text, int nIndex, int eIndex) {
        SpannableString span = new SpannableString(text);
        span.setSpan(new AbsoluteSizeSpan(14, true), 0, nIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.tj_text_content_3)),
                0, nIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new AbsoluteSizeSpan(10, true), nIndex, eIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.tj_text_content_9)),
                nIndex, eIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return span;
    }

    //输入过滤器
    InputFilter pointFilter = new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dStart, int dEnd) {
            if (source.toString().equals("")) {
                return null;
            }
            String dValue = dest.toString();
            String splitArray[] = dValue.split("\\.");
            //含有小数位
            if (splitArray.length > 1) {
                String dotValue = splitArray[1];
                int diff = dotValue.length() - 1;//只能输入两位小数
                if (diff > 0) {
                    return source.subSequence(start, end - diff);
                }
            } else {     //不含小数,限制输入为6位
                if (dValue.length() > 5) {
                    int diff = dValue.length() - 5;
                    return source.subSequence(start, end - diff);
                }
            }
            return null;
        }
    };


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.submit_recharge:
                submitRecharge();
                break;
            case R.id.money_five_hundred:
                selectMoneyText(MONEY_500);
                break;
            case R.id.money_two_hundred:
                selectMoneyText(MONEY_200);
                break;
            case R.id.money_hundred:
                selectMoneyText(MONEY_100);
                break;
            case R.id.money_fivty:
                selectMoneyText(MONEY_50);
                break;
            case R.id.money_other:
                selectCustomMoney();
                break;
            case R.id.activity_money_alipay:
                setPayWay(PAY_WITH_ALIPAY);
                break;
            case R.id.activity_money_wechat:
                setPayWay(PAY_WITH_WECHAT);
                break;
            default:
                break;
        }
    }

    private void selectMoneyText(int type) {
        setTextStyle(type);
        mEdtInputMoney.setFocusable(false);
        mEdtInputMoney.setText("");
        mEdtInputMoney.setBackgroundResource(R.drawable.bg_textfield_disabled_sprite);
    }

    private void selectCustomMoney() {
        setTextStyle(MONEY_CUSTOM);
        mEdtInputMoney.setFocusableInTouchMode(true);
        mEdtInputMoney.setBackgroundResource(R.drawable.bg_textfield_normal_sprite);
    }

    private void submitRecharge() {
        if (checkInput()) {
            if (mFlagPay == PAY_WITH_ALIPAY) {
                payWithAli();//支付宝支付
            } else if (mFlagPay == PAY_WITH_WECHAT) {
                payWithWeiXin();//微信支付
            }
        }
    }

    private boolean checkInput() {
        if (mFlagPay != PAY_WITH_ALIPAY && mFlagPay != PAY_WITH_WECHAT) {
            Snackbar.make(mEdtInputMoney, "请至少选择一种支付方式！", Snackbar.LENGTH_SHORT).show();
            return false;
        }
        if (mIndexPAY < 0 || mIndexPAY > 4) {
            Snackbar.make(mEdtInputMoney, "请至少选择一种金额！", Snackbar.LENGTH_SHORT).show();
            return false;
        }
        if (mIndexPAY == 4) {
            String money = mEdtInputMoney.getText().toString().trim();
            if (money.equals("") || money.equals("")) {
                Snackbar.make(mEdtInputMoney, "请输入正确的金额！", Snackbar.LENGTH_SHORT).show();
                return false;
            }
            try {
                double t = Double.valueOf(money);
                if (t < 0.01d) {
                    Snackbar.make(mEdtInputMoney, "最低充值金额为0.01元", Snackbar.LENGTH_SHORT).show();
                    return false;
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
                Snackbar.make(mEdtInputMoney, "请输入正确的金额！", Snackbar.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    //支付宝请求支付
    private void payWithAli() {
        showMyProgressDialog(true, false, "提交中...");
        mMainRequest = ChargeStationAPI.payWithAli(getMoneyOfAli(), new EHttpResponse() {

            @Override
            public void onEResponse(String response) {
                JsonAlipay result = GsonUtils.toBean(JsonAlipay.class, response);
                if (handleResponseStatus(result)) {
                    mAlipaySign = result.sign;
                    mTradingNumber = result.tradingNo;
                    //支付完成标志
                    WXPayEntryActivity.this.setResult(Const.CODE_REQUEST_RECHARGE_SUCCESS);

                    Runnable payRunnable = new Runnable() {

                        @Override
                        public void run() {
                            // 构造PayTask 对象
                            PayTask alipay = new PayTask(WXPayEntryActivity.this);
                            // 调用支付接口，获取支付结果
                            String result = alipay.pay(mAlipaySign);


                            Message msg = alipayHandle.obtainMessage();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            alipayHandle.sendMessage(msg);
                        }
                    };
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                }
            }

            @Override
            public void onEErrorResponse(VolleyError error) {
                Toast.makeText(mContext, R.string.common_tip_resultfail, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onEFinish() {
                super.onEFinish();
                dismissMyProgressDialog();
            }
        });
    }

    private double getMoneyOfAli() {
        if (mIndexPAY == MONEY_500) {
            return 500;
        } else if (mIndexPAY == MONEY_200) {
            return 200;
        } else if (mIndexPAY == MONEY_100) {
            return 100;
        } else if (mIndexPAY == MONEY_50) {
            return 50;
        } else if (mIndexPAY == MONEY_CUSTOM) {
            String money = mEdtInputMoney.getText().toString().trim();
            return Double.valueOf(money);
        }
        return 0;
    }

    private void payWithWeiXin() {
        if (!msgApi.isWXAppInstalled()) {
            Snackbar.make(mEdtInputMoney, "您还未安装微信客户端", Snackbar.LENGTH_SHORT).show();
            return;
        }
        genPayReq();
    }

    //微信请求支付
    private void genPayReq() {
        showMyProgressDialog(true, false, "提交中...");
        mMainRequest = ChargeStationAPI.payWithWeixin(getMoneyOfWeiXin(),
                new EHttpResponse() {

                    @Override
                    public void onEResponse(String response) {
                        JsonWxPay result = GsonUtils.toBean(JsonWxPay.class, response);
                        if (handleResponseStatus(result)) {
                            PayReq req = new PayReq();
                            req.appId = result.appid;
                            req.partnerId = result.partnerid;
                            req.prepayId = result.prepayid;
                            req.packageValue = "Sign=WXPay";
                            req.nonceStr = result.noncestr;
                            req.timeStamp = result.timestamp;
                            req.sign = result.sign;
                            mTradingNumber = result.tradingNo;
                            msgApi.registerApp(getResources().getString(R.string.weixin_app_id));
                            msgApi.sendReq(req);
                            //支付完成标志
                            WXPayEntryActivity.this.setResult(Const.CODE_REQUEST_RECHARGE_SUCCESS);
                        }
                    }

                    @Override
                    public void onEErrorResponse(VolleyError error) {
                        Toast.makeText(mContext, R.string.common_tip_resultfail, Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onEFinish() {
                        super.onEFinish();
                        dismissMyProgressDialog();
                    }

                });
    }

    private int getMoneyOfWeiXin() {
        if (mIndexPAY == MONEY_500) {
            return 50000;
        } else if (mIndexPAY == MONEY_200) {
            return 20000;
        } else if (mIndexPAY == MONEY_100) {
            return 10000;
        } else if (mIndexPAY == MONEY_50) {
            return 5000;
        } else if (mIndexPAY == MONEY_CUSTOM) {
            String money = mEdtInputMoney.getText().toString().trim();
            double t = Double.valueOf(money);
            return (int) (t * 100);
        }
        return 0;
    }

    private void setPayWay(int payWay) {
        if (payWay == PAY_WITH_WECHAT) {
            mLayoutAlipay.setBackgroundResource(R.drawable.bg_select_box_active_disabled);
            mLayoutWechat.setBackgroundResource(R.drawable.bg_select_box_active_sprite);
            mFlagPay = PAY_WITH_WECHAT;
        } else {
            mLayoutAlipay.setBackgroundResource(R.drawable.bg_select_box_active_sprite);
            mLayoutWechat.setBackgroundResource(R.drawable.bg_select_box_active_disabled);
            mFlagPay = PAY_WITH_ALIPAY;
        }
    }

    private void setTextStyle(int index) {
        mTexMoneyArrays[mIndexPAY].setBackgroundResource(R.drawable.bg_select_box_active_disabled);
        mTexMoneyArrays[index].setBackgroundResource(R.drawable.bg_select_box_active_sprite);
        mIndexPAY = index;
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq arg0) {

    }

    //微信支付结果回调
    @Override
    public void onResp(BaseResp resp) {
        Log.d(TAG, "onPayFinish, errCode = " + resp.errCode);
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            //回调结果
            if (resp.errCode == 0) {
                Toast.makeText(mContext, "支付成功", Toast.LENGTH_LONG).show();
            } else if (resp.errCode == -2) {
                //用户取消
                cancelPay();
                Toast.makeText(mContext, "支付失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //取消支付
    private void cancelPay() {
        //请求取消支付
        ChargeStationAPI.cancelRecharge(mTradingNumber, mEmptyResponse);
    }

    private static EHttpResponse mEmptyResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
        }
    };


    private static class AlipayHandle extends Handler {
        WeakReference<WXPayEntryActivity> mActivity;

        AlipayHandle(WXPayEntryActivity activity) {
            mActivity = new WeakReference<WXPayEntryActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            WXPayEntryActivity theActivity = mActivity.get();
            if (theActivity != null) {
                switch (msg.what) {
                    case SDK_PAY_FLAG:
                        PayResult payResult = new PayResult((String) msg.obj);
                        //获取支付结果返回码
                       //9000——订单支付成功 8000——正在处理中 4000——订单支付失败
                       //5000——重复请求 6001——用户中途取消 6002——网络连接出错
                        String resultStatus = payResult.getResultStatus();
                        System.out.println("resultStatus------------->>" + resultStatus);
                        //判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, "9000")) {
                            Toast.makeText(theActivity, "支付成功", Toast.LENGTH_SHORT).show();
                        } else {
                            // 判断resultStatus 为非“9000”则代表可能支付失败
                            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            if (TextUtils.equals(resultStatus, "8000")) {
                                Toast.makeText(theActivity, "支付结果确认中", Toast.LENGTH_SHORT).show();
                            } else {
                                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                                //用户中途取消
                                if (TextUtils.equals(resultStatus, "6001")) {
                                    //请求取消支付
                                    ChargeStationAPI.cancelRecharge(mTradingNumber, mEmptyResponse);
                                }
                                Toast.makeText(theActivity, "支付失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                        break;
                    default:
                        break;
                }
            }

        }
    }


}


